﻿using Abp.Application.Navigation;
using Abp.Threading;
using Abp.UI;
using MyCompanyName.AbpZeroTemplate.Authorization.Users;
using MyCompanyName.AbpZeroTemplate.Organizations;
using MyCompanyName.AbpZeroTemplate.Prm;
using MyCompanyName.AbpZeroTemplate.Prm.Admin;
using MyCompanyName.AbpZeroTemplate.Prm.Document;
using MyCompanyName.AbpZeroTemplate.Prm.Project;
using MyCompanyName.AbpZeroTemplate.Prm.Project.Dto;
using MyCompanyName.AbpZeroTemplate.Prm.Topic;
using MyCompanyName.AbpZeroTemplate.Sessions;
using MyCompanyName.AbpZeroTemplate.Web.Areas.Mpa.Models.Layout;
using MyCompanyName.AbpZeroTemplate.Web.Areas.Prm.Startup;
using MyCompanyName.AbpZeroTemplate.Web.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace MyCompanyName.AbpZeroTemplate.Web.Areas.Prm.Controllers
{
    public class SummaryController : AbpZeroTemplateControllerBase
    {
        private readonly ISummaryAppService _summaryManager;
        private readonly IDocumentAppService _docService;
        private readonly IProjectAppService _proService;
        private readonly IProjectRoleAppService _proRoleService;
        private readonly ITopicAppService _questionService;
        private readonly IProjectTaskAppService _taskService;
        private readonly IUserAppService _userService;


        public SummaryController(
            ISummaryAppService summaryManager,
            IDocumentAppService docService,
            IProjectAppService proService,
            IProjectRoleAppService proRoleService,
            ITopicAppService questionService,
            IProjectTaskAppService taskService,
            IUserAppService userService
            )
        {
            _summaryManager = summaryManager;
            _docService = docService;
            _proService = proService;
            _proRoleService = proRoleService;
            _questionService = questionService;
            _taskService = taskService;
            _userService = userService;
        }

        /// <summary>
        /// 项目完成情况通报
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            /*
             * 每周一发送统计项》》》》》》
             * 统计对象==> 所有的进行中的项目；
             * 发送目标==> 【所有项目负责人+上级quan的人员（一级）】1+【各个销售单独发送】N{根据客户（仅对项目经理 + 上级圈的人员公开）来分辨}
             * 项目经理 | 项目编号 | 预计完成（顺序）| 进度（%）| 阶段进展（已完成个数/所有个数） | 文档数（本周提交数/累计上传文档数据）| 问题（本周新增/所有问题数）|任务数（本周完成|本周新增）
             * -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
             * 
             */

            var dt = DateTime.Now.AddDays(-7);
            var mondayDate = DateHelper.GetMondayDate(dt);
            var doingProjects = _summaryManager.GetWeekSummaryProjects(mondayDate);
            List<WeekSummaryDataDto> lst = new List<WeekSummaryDataDto>();
            foreach (var item in doingProjects)
            {
                int totalDays = (item.PlanEndDate.Date - item.PlanStartDate.Date).Days + 1;
                int doingDays = DateTime.Now.Date >= item.PlanStartDate ? (DateTime.Now.Date - item.PlanStartDate.Date).Days + 1 : 0;
                if (doingDays > totalDays)
                { doingDays = totalDays; }
                lst.Add(new WeekSummaryDataDto()
                {
                    ProId = item.Id,
                    Admin = _userService.GetUserName(item.PMId),
                    AdminId = item.PMId,
                    ProNo = item.ProjectNo,
                    AllDocCount = _docService.GetDocumentCount(item.Id),
                    LastUploadDocCount = _docService.GetDocumentCount(item.Id, mondayDate),
                    AllQuestionCount = _questionService.GetTopicCount(item.Id),
                    LastAddQuestionCount = _questionService.GetTopicCount(item.Id, mondayDate),
                    FinishedPhase = _proService.GetProjectPhaseFinishedCount(item.Id),
                    TotalPhase = _proService.GetProjectPhaseCount(item.Id),
                    LastAddTaskCount = _taskService.GetNewTaskCount(item.Id, mondayDate),
                    LastFinishTaskCount = _taskService.GetCloseTaskCount(item.Id, mondayDate),
                    PlanEnd = item.PlanEndDate,
                    SalorId = 0,
                    SalorName = "",
                    DoingRate = string.Format("{0}%", (doingDays * 1.0 * 100 / totalDays).ToString("F0"))
                });
            }

            ViewBag.WebRoot = System.Configuration.ConfigurationManager.AppSettings["fileServer"];
            // projectProgress.Where(x=>x.Status== Status.进行中)
            return View(lst);
        }

        /// <summary>
        /// 周报填写情况
        /// </summary>
        /// <returns></returns>
        public ActionResult WeekReport()
        {
            /*周一早上发送
             * 按照项目，分别发送各自周报情况
             * 0、统计对象==> 项目角色管理，设定哪些角色，需要提交项目周报；
             * 1、发送目标==> 项目经理
             * 2、发送内容==> 人员+周次+周报链接（项目文档的目录）
             * 3、项目成员管理，增加【退出】按钮，表示何时离开了该项目组，显示{张三[16.12.1~17.1.18]}
             */

            string root = System.Configuration.ConfigurationManager.AppSettings["fileServer"];

            var dt = DateTime.Now;
            var curMonday = DateHelper.GetMondayDate(dt);
            var preMonday = curMonday.AddDays(-7);

            var projects = _summaryManager.GetWeekSummaryProjects(preMonday);

            WebDownload WebClientObj = new WebDownload();
            WebClientObj.Encoding = System.Text.Encoding.UTF8;
            foreach (var item in projects)
            {
                string url = string.Format("{0}/Prm/Summary/ProjectWeekDoc?projectId={1}&proNo={2}", root, item.Id, item.ProjectNo);
                string html = WebClientObj.DownloadString(url);
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["明细"] = html;
                dic["项目编号"] = item.ProjectNo;
                _proService.CreateMail(dic, (int)MailCatelog.项目周报完成情况, item.Id);
            }
            return Content("success");
        }

        public ActionResult InquiryNoReset()
        {
            _proService.ResetQuriyNo();
            return Content("success");
        }

        public ActionResult ProjectReport()
        {
            /*
            * 每周一发送统计项》》》》》》
            * 统计对象==> 所有的进行中的项目；
            * 发送目标==> 【所有项目负责人+上级quan的人员（一级）】1+【各个销售单独发送】N{根据客户（仅对项目经理 + 上级圈的人员公开）来分辨}
            * 项目经理 | 项目编号 | 预计完成（顺序）| 进度（%）| 阶段进展（已完成个数/所有个数） | 文档数（本周提交数/累计上传文档数据）| 问题（本周新增/所有问题数）|任务数（本周完成|本周新增）
            * -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            * 
            */

            string root = System.Configuration.ConfigurationManager.AppSettings["fileServer"];

            var dt = DateTime.Now.AddDays(-7);
            var curMonday = DateHelper.GetMondayDate(dt);
            var doingProjects = _summaryManager.GetWeekSummaryProjects(curMonday);
            List<int> PMids = doingProjects.Select(x => x.PMId).Distinct().ToList();


            WebDownload WebClientObj = new WebDownload();
            WebClientObj.Encoding = System.Text.Encoding.UTF8;

            string url = string.Format("{0}/Prm/Summary/Index", root);
            string html = WebClientObj.DownloadString(url);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["明细"] = html;
            dic["周"] = string.Format("{0}", DateHelper.GetWeek(curMonday));
            _proService.CreateMail(dic, (int)MailCatelog.项目进展公告, string.Join(",", PMids));
            return Content("success");
        }

        /// <summary>
        /// 上周周报提交情况
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="proNo"></param>
        /// <returns></returns>
        public ActionResult ProjectWeekDoc(int projectId = 2, string proNo = "")
        {
            string root = System.Configuration.ConfigurationManager.AppSettings["fileServer"];
            DateTime dts = DateTime.Now.AddDays(-7);
            DateTime preMonday = DateHelper.GetMondayDate(dts);
            var teams = _proService.GetWeekProjectTeam(projectId, preMonday);
            var docs = _docService.GetWeekDocument(new List<int>() { projectId });
            var nowWeek = DateHelper.GetWeek(DateTime.Now);
            teams = teams.Where(x => x.week != nowWeek).ToList();
            foreach (var item in teams)
            {
                var weekReport = docs.Where(x => x.ReportDate >= item.dts && x.ReportDate < item.dte).ToList();
                if (weekReport.Count > 0)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (var report in weekReport)
                    {
                        sb.Append(string.Format("<a href='{0}'>{1}</a><br/>", string.Format("{0}/prm/home/DownloadAuthFile?path={1}", root, report.FullUrl), report.Name));
                    }
                    item.FileName = sb.ToString();
                }
                else
                {
                    item.FileName = " 未提交 ";
                }
            }
            ViewBag.ProNo = proNo;
            return View(teams);
        }


        public ActionResult ProjectWeekTask()
        {
            string root = System.Configuration.ConfigurationManager.AppSettings["fileServer"];
            var teams = _proService.GetWeekProjectTeam();
            var proIds = teams.Select(x => x.proId).Distinct().ToList();
            var docs = _docService.GetWeekDocument(proIds);

            int ignoreWeek = DateHelper.GetWeek(DateTime.Now);
            foreach (var item in teams)
            {
                item.FileName = "";
                var weekReport = docs.Where(x => x.proId == item.proId && x.ReportDate >= item.dts && x.ReportDate < item.dte).ToList();
                if (weekReport.Count > 0)
                {
                    item.FileName = "已提交";
                }
            }
            var unCommitTeams = teams.Where(x => x.FileName == "" && x.week != ignoreWeek).ToList();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (var proId in proIds)
            {
                sb = new System.Text.StringBuilder();
                var __unCommitTeams = unCommitTeams.Where(x => x.proId == proId).ToList();
                int t = 0;
                var _weeks = __unCommitTeams.Select(x => x.week).Distinct().ToList();
                if (_weeks.Count == 0)
                {
                    continue;//没有周报的情况
                }
                string proNo = _proService.GetProNo(proId);
                sb.AppendFormat("<br>项目：<a  target='_blank' href='{2}/PRM/home/index#app.prm.detail.Index/{3}'>{0}</a>  有 {1} 份周报需要提交<br>", proNo, _weeks.Count, root, proId);
                foreach (var week in _weeks)
                {
                    var first = __unCommitTeams.Where(x =>  x.week == week).FirstOrDefault();
                    sb.AppendFormat("   第{0}周({1}~{2});", week, first.dts.ToString("yyyy/MM/dd"), first.dte.ToString("yyyy/MM/dd"));
                }
                t = t + _weeks.Count;

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["明细"] = sb.ToString();
                dic["待提交数"] = string.Format("{0}", t);
                _proService.CreateMail(dic, (int)MailCatelog.个人未提交周报提醒, proId);
            }

            return Content("success");
        }

    }
}